#!/bin/sh

# services for brew on macOS
# services batch for thinBar devops

# SERVERS=("mariadb" "redis" "php@7.1" "mongodb" "nginx")
SERVERS=("mariadb" "redis" "php" "mongodb" "nginx" "mysql" "php@5.6" "php@7.1")

set_brew_service()
{
    echo "brew services status..."
    while read -r LINE; do
        echo $LINE

        svrname="$(echo $LINE | awk '{print $1}')"
        svrstatus="$(echo $LINE | awk '{print $2}')"

        for((i=0;i<${#SERVERS[*]};i++))
        do
            if [ "${SERVERS[$i]}" == "${svrname}" ]; then
                if [ "$1" == "start" ]; then
                    if [ "$svrstatus" == "stopped" ]; then
                        if [ "$svrname" == "nginx" ]; then
                            sudo brew services restart $svrname
                        else
                            brew services run $svrname
                        fi
                    fi
                else
                    if [ "$svrstatus" == "started" ]; then
                        if [ "$svrname" == "nginx" ]; then
                            sudo brew services stop $svrname
                        else
                            brew services stop $svrname
                        fi
                    fi
                fi
            fi
        done

    done <<< "$(echo "$(brew services list | sed 1,1d | awk '{print $1,$2}')")"
}

if [ "$1" == "start" ]; then
    set_brew_service "$1"
elif [ "$1" == "stop" ]; then
    set_brew_service "$1"
else
    echo "{$1} parameter error, plese input 'start' or 'stop'"
    exit 1
fi

brew services list


#brew services run mariadb
#brew services run php71
#brew services run redis
#brew services run mongodb
#sudo brew services start nginx 
